﻿@using System.IO
@using System.Net
@using AntBlazor.Docs.Highlight
@using Markdig
@using Markdig.Extensions.Yaml
@using Markdig.Syntax
@using YamlDotNet.Serialization

@inherits ComponentBase
@inject HtmlRenderService HtmlRenderService
@inject HttpClient HttpClient
@inject IPrismHighlighter PrismHighlighter

<h1>@title</h1>

@((MarkupString)html)

@code {

    [Parameter] public string DocUrl { get; set; }

    [Parameter] public string MarkdownText { get; set; }

    [Parameter]
    public RenderFragment ChildContent { get; set; }

    string html { get; set; }

    string title { get; set; }

    protected override async Task OnParametersSetAsync()
    {
        if (!string.IsNullOrEmpty(DocUrl))
        {
            MarkdownText = await this.HttpClient.GetStringAsync(DocUrl);
        }

        if (ChildContent != null)
        {
            MarkdownText = await HtmlRenderService.RenderAsync(ChildContent);
            MarkdownText = WebUtility.HtmlDecode(MarkdownText);
        }

        if (!string.IsNullOrEmpty(MarkdownText))
        {
            MarkdownText = MarkdownText.Trim(' ', '\r', '\n');
            var pipeline = new MarkdownPipelineBuilder()
                .UseYamlFrontMatter()
                .UsePipeTables()
                .Build();

            StringWriter writer = new StringWriter();
            var renderer = new Markdig.Renderers.HtmlRenderer(writer);
            pipeline.Setup(renderer);

            MarkdownDocument document = Markdig.Markdown.Parse(MarkdownText, pipeline);
            var yamlBlock= document.Descendants<YamlFrontMatterBlock>().FirstOrDefault();

            if (yamlBlock != null)
            {
                string yaml = MarkdownText.Substring(yamlBlock.Span.Start, yamlBlock.Span.Length).Trim('-');
                var meta = new Deserializer().Deserialize<Dictionary<string, string>>(yaml);

                title = meta["title"];
            }

            renderer.Render(document);
            writer.Flush();
            html = writer.ToString();

        }
    }

    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
        await PrismHighlighter.HighlightAllAsync();
    }

}
